package com.example.springlog.config.log;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import com.example.springlog.converter.DesensitiveMessageConverter;
import com.example.springlog.entity.DesensitiveRule;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 日志功能开关配置类
 * @Author: 刘超
 * @Date: 2023-06-03 16:23
 */
@Component
public class LoggerConfig {
    /**
     * 日志级别
     */
    private String level = "INFO";

    /**
     * 脱敏标识
     */
    private boolean desensitive = true;

    /**
     * 脱敏规则
     */
    private List<DesensitiveRule> rules = new ArrayList<>();

    @PostConstruct
    public void init(){
        if (!CollectionUtils.isEmpty(rules)) {
            this.setRules(rules);
        }
        if (desensitive){
            LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
            if (!DesensitiveMessageConverter.DESENSITIVE_TRUE.equals(loggerContext.getProperty(DesensitiveMessageConverter.DESENSITIVE_KEY))) {
                setDesensitive(desensitive);
            }
        }
    }

    public String getLevel() {
        return level;
    }

    public void setLevel(String level) {
        if (!StringUtils.hasLength(level) || this.level.equalsIgnoreCase(level)) {
            return;
        }
        this.level = level;
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        // 设置缓存中每一个Logger的等级
        for (ch.qos.logback.classic.Logger logger : loggerContext.getLoggerList()) {
            logger.setLevel(Level.toLevel(level, logger.getLevel()));
        }
    }

    public boolean isDesensitive() {
        return desensitive;
    }

    public void setDesensitive(boolean desensitive) {
        this.desensitive = desensitive;
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        String desensitiveFlag;
        if (this.desensitive) {
            desensitiveFlag = DesensitiveMessageConverter.DESENSITIVE_TRUE;
        } else {
            desensitiveFlag = DesensitiveMessageConverter.DESENSITIVE_FALSE;
        }
        loggerContext.putProperty(DesensitiveMessageConverter.DESENSITIVE_KEY, desensitiveFlag);

    }

    public List<DesensitiveRule> getRules() {
        return rules;
    }

    public void setRules(List<DesensitiveRule> rules) {
        if (CollectionUtils.isEmpty(rules)) {
            return;
        }
        this.rules = rules;
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        loggerContext.putObject(DesensitiveMessageConverter.DESENSITIVE_RULE,rules);
    }
}
